﻿namespace Eldert.BTUG.IoT.Management.IoTHub.Devices
{
    using System.Threading.Tasks;

    using Microsoft.Azure.Devices;
    using Microsoft.Azure.Devices.Common.Exceptions;

    /// <summary>
    /// Class used to do device management in IoT Hub.
    /// </summary>
    public class DeviceManagement
    {
        // TODO: Use your own settings here.

        /// <summary>
        /// The registry manager used to manage our IoT Hub.
        /// </summary>
        private static readonly RegistryManager registryManager =
            RegistryManager.CreateFromConnectionString("HostName=your-host-name;SharedAccessKeyName=your-sas-name;SharedAccessKey=your-sas-key");

        /// <summary>
        /// Add device to IoT Hub
        /// </summary>
        /// <param name="deviceID">
        /// The device's ID.
        /// </param>
        /// <returns>
        /// Task <see cref="Task"/> which will return the PK of the device.
        /// </returns>
        public static async Task<string> AddDevice(string deviceID)
        {
            // Device to be added
            Device device;

            try
            {
                // Add new device
                device = await registryManager.AddDeviceAsync(new Device(deviceID));
            }
            catch (DeviceAlreadyExistsException)
            {
                // Get existing device
                device = await registryManager.GetDeviceAsync(deviceID);
            }

            // Return the PK for the device
            return device.Authentication.SymmetricKey.PrimaryKey;
        }
    }
}
